package com.patchmanage.back.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class PropertyUtilsEx
{
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtilsEx.class);
    private static final String CONFIG_FILE = "application.properties";
    private static Map<String, Properties> pMap = new HashMap();

    private static synchronized Properties get(String propertyFileName)
    {
        propertyFileName = StrUtil.isNotBlank(propertyFileName) ? propertyFileName : "application.properties";

        Properties p = (Properties)pMap.get(propertyFileName);

        if (p == null)
        {
            try
            {
                p = PropertiesLoaderUtils.loadProperties(new ClassPathResource(propertyFileName));

                if (p != null) {
                    pMap.put(propertyFileName, p);
                    logger.info("配置文件[{}],装载成功~", new Object[] { propertyFileName });
                } else {
                    logger.info("配置文件[{}],装载失败!", new Object[] { propertyFileName });
                }
            } catch (IOException e) {
                logger.error("配置文件 [" + propertyFileName + "] ,装载异常:" + e.getMessage(), e);
            }
        }

        return p;
    }

    public static void reload() {
        reload("application.properties");
    }

    public static void reload(String filename) {
        if (pMap.get(filename) != null) {
            ((Properties)pMap.get(filename)).clear();
        }
        get(filename);
    }
}